from pyson.gen import PysonObject, boolean, string, struct
from pyduct.handlers import CookieFragmentBuilder, MessageFragment
from scala import Function1, Option
from scala.collection.mutable import StringBuilder

NONE = Option.apply(None)

class ValidationInfo(PysonObject):
    isValid = boolean()
    message = string()

class ValidationInfoHolder(PysonObject):
    ValidationInfo = struct(ValidationInfo)

class CookieValidationBuilder(CookieFragmentBuilder):

    def getCookieMessageFragmentClass(self, cookieGateway, property):
        ve = cookieGateway.validationException()
        if (ve is not None):
            class findPropertyViolation(Function1):
                def apply(self, violation):
                    path = violation.getPropertyPath()
                    iterator = path.iterator()
                    pathBuilder = StringBuilder()
                    while iterator.hasNext():
                        node = iterator.next()
                        if not pathBuilder.isEmpty:
                            pathBuilder.append('.')
                        if node.getName() is not None:
                            pathBuilder.append(node.getName())

                    return pathBuilder.toString() == property.name()

            violOpt = ve.violationSet().find(findPropertyViolation())
            if violOpt is NONE:
                return None
            else:
                violation = violOpt.get()
                class Fragment(ValidationInfoHolder, MessageFragment):
                    def __init__(self):
                        super(Fragment, self).__init__()
                        self.ValidationInfo.isValid = 0
                        self.ValidationInfo.message = violation.getMessage()

                return Fragment
        else:
            return None

def getBuilders():
    return (CookieValidationBuilder,)